package cn.edu.scujcc.helloworld.api;

import android.util.Log;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import cn.edu.scujcc.helloworld.util.AppConfig;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


//封装请求服务器代码
public class Api {
    public static OkHttpClient client;
    public static String requestUrl;
    private static HashMap<String,Object>mParams;
    public static Api api = new Api();
    public Api(){

    }

    public static Api config(String url, HashMap<String,Object>params){
        client = new OkHttpClient.Builder()
                .build();
        requestUrl = ApiConfig.BASE_URL + url;
        mParams = params;
        return api;
    }

    public static void postRequest(final TtitCallback callback){
        JSONObject jsonObject = new JSONObject(mParams);
        String jsonStr = jsonObject.toString();
        RequestBody requestBodyJson =
                RequestBody.create(MediaType.parse("application/json;charset=utf-8")
                        ,jsonStr);
        //创建Rquest
        Request request = new  Request.Builder()
                .url(requestUrl)
                .addHeader("contentType","application/json;charset=UTF-8")
                .post(requestBodyJson)
                .build();
        //创建 call回调对象
        final Call call = client.newCall(request);
        //发起请求
        call.enqueue(new Callback(){
            @Override
            //请求失败回调
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure",e.getMessage());
                callback.onFailure(e);
            }

            @Override
            //请求成功回调
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
               callback.onSuccess(result);
            }
        });
    }
}
